/**
 * 
 */
package com.swg.cocobox.message.internal;

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.swg.cocobox.message.ClientInfo;
import com.swg.cocobox.message.ClientInfoParser;

/**
 * @author satriaprayoga
 *
 */
public final class EncodedClientInfoParser implements ClientInfoParser{
	
	private final static String REGEX="(\\G\\s*?\\{\\s*?(((username|password){1}\\s*?:\\s*?([A-Za-z0-9\\_\\@]*?){1}))\\s*?\\}\\s*?)\\1*?";
	
	private final static Pattern PATTERN=Pattern.compile(REGEX,Pattern.CASE_INSENSITIVE);
	
	private final Charset charset;
	
	public EncodedClientInfoParser(Charset charset) {
		this.charset=charset;
	}

	@Override
	public ClientInfo parseClientInfo(byte[] data) {
		String input=new String(data,charset);
		input=input.trim();
		Matcher matcher=PATTERN.matcher(input);
		String username = null;
		String password = null;
		ClientInfo info=null;
		while(matcher.find()){
			if(matcher.group(4).equalsIgnoreCase("username")){
				username=matcher.group(5).trim();
			}else if(matcher.group(4).equalsIgnoreCase("password")){
				password=matcher.group(5).trim();
			}
		}
		if(username==null && password==null){
			info=null;
		}else{
			info=new SimpleClientInfo(username, password);
		}
		
		return info;
	}

}
